package com.pmt.feedplayer.core

import android.content.Context
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
// 使用别名导入Android系统的SpeechRecognizer
import android.speech.SpeechRecognizer as AndroidSpeechRecognizer
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.Locale

/**
 * Android平台语音识别器实现
 */
class AndroidSpeechRecognizer(private val context: Context) : SpeechRecognizer {
    private var recognizer: AndroidSpeechRecognizer? = null
    private var languageCode = "ja-JP" // 默认日语
    private var lastConfidence: Float? = null
    
    init {
        // 检查设备是否支持语音识别
        if (AndroidSpeechRecognizer.isRecognitionAvailable(context)) {
            recognizer = AndroidSpeechRecognizer.createSpeechRecognizer(context)
            println("语音识别器初始化成功")
        } else {
            // 优雅处理：不抛出异常，而是记录日志
            println("警告: 当前设备不支持语音识别功能")
            recognizer = null
        }
    }
    
    override suspend fun recognize(audioData: ByteArray): String = withContext(Dispatchers.Main) {
        // 如果语音识别器不可用，返回空字符串
        if (recognizer == null) {
            return@withContext ""
        }
        
        val resultDeferred = CompletableDeferred<String>()
        
        val listener = object : RecognitionListener {
            override fun onReadyForSpeech(params: Bundle?) {
                // 准备开始识别
            }
            
            override fun onBeginningOfSpeech() {
                // 开始说话
            }
            
            override fun onRmsChanged(rmsdB: Float) {
                // 音量变化
            }
            
            override fun onBufferReceived(buffer: ByteArray?) {
                // 接收音频缓冲区
            }
            
            override fun onEndOfSpeech() {
                // 结束说话
            }
            
            override fun onError(error: Int) {
                val errorMessage = when (error) {
                    AndroidSpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "网络超时"
                    AndroidSpeechRecognizer.ERROR_NETWORK -> "网络错误"
                    AndroidSpeechRecognizer.ERROR_AUDIO -> "音频错误"
                    AndroidSpeechRecognizer.ERROR_SERVER -> "服务器错误"
                    AndroidSpeechRecognizer.ERROR_CLIENT -> "客户端错误"
                    AndroidSpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "语音超时（无语音输入）"
                    AndroidSpeechRecognizer.ERROR_NO_MATCH -> "未找到匹配项"
                    AndroidSpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "识别器繁忙"
                    AndroidSpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "权限不足"
                    else -> "未知错误: $error"
                }
                println("Speech recognition error: $errorMessage")
                resultDeferred.complete("") // 返回空字符串而不是异常，允许处理继续
            }
            
            override fun onResults(results: Bundle?) {
                val matches = results?.getStringArrayList(AndroidSpeechRecognizer.RESULTS_RECOGNITION)
                val confidenceScores = results?.getFloatArray(AndroidSpeechRecognizer.CONFIDENCE_SCORES)
                
                if (matches?.isNotEmpty() == true) {
                    val recognizedText = matches[0]
                    lastConfidence = confidenceScores?.getOrNull(0)
                    resultDeferred.complete(recognizedText)
                } else {
                    resultDeferred.complete("")
                }
            }
            
            override fun onPartialResults(partialResults: Bundle?) {
                // 处理部分结果（可选）
            }
            
            override fun onEvent(eventType: Int, params: Bundle?) {
                // 处理事件
            }
        }
        
        recognizer?.setRecognitionListener(listener)
        
        // 配置识别意图
        val intent = RecognizerIntent.getVoiceDetailsIntent(context)
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, languageCode)
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName)
        intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 1000) // 1秒
        intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, 500) // 500ms
        
        try {
            // 注意：这里使用的是标准的语音识别流程，对于直接处理音频数据，需要更复杂的实现
            // 实际项目中可能需要使用AudioRecord录制音频并处理，或者使用更专业的API
            recognizer?.startListening(intent)
            
            // 设置超时处理
            val recognizedText = resultDeferred.await()
            return@withContext recognizedText
        } catch (e: Exception) {
            println("Speech recognition failed: ${e.message}")
            return@withContext ""
        }
    }
    
    override fun stop() {
        recognizer?.stopListening()
    }
    
    override fun setLanguage(languageCode: String) {
        this.languageCode = languageCode
    }
    
    override fun getConfidence(): Float? {
        return lastConfidence
    }
    
    /**
     * 释放资源
     */
    fun release() {
        recognizer?.destroy()
        recognizer = null
    }
}